package cz.cvut.sefcijak.zatacka;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.*;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;


import android.*;

/**
 * Created with IntelliJ IDEA.
 * User: sefcijak
 * Date: 25.3.13
 * Time: 9:37
 */
public class GameActivity extends Activity {
    //////////////////////////////////////////////////////////////////////////////////
    //debug
    private static final String TAG = "DEBug";
    //boolean proměné
    public static boolean zapnuto = false;
    public static boolean prvniZapnuto = true;
    //plocha
    public static KresliView kresli;
    public static Display thisDisplay;
    public static Bod maxBod = new Bod();
    public static int okraj = 1;
    //cas
    public static int  tak1 = 0,tak2 = 0;
   //handler
    enum PrikazyHandler {
        START,
        MISTNIHAD,
        KOLIZE,
        NAZIVOT,
        VZDALENE
    }
    static PrikazyHandler[] prikazHandler = PrikazyHandler.values();
    //dialog
    public static AlertDialog dialog;
    //hadi
    public static int fps = 50;
    protected static Had had1 = null;
    protected static Had had2 = null;
    /*protected Had had3 = null;
    protected Had had4 = null;*/

    //////////////////////////////////////////////////////////////////////////////////

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Set full screen view
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        thisDisplay = getWindowManager().getDefaultDisplay();

        maxBod.x = this.getResources().getDisplayMetrics().widthPixels;
        maxBod.y = this.getResources().getDisplayMetrics().heightPixels;

        kresli = new KresliView(this);
        setContentView(kresli);
        //drawView.requestFocus();
        okraj = 8;

        had1 = new Had("HAD 1",Color.YELLOW);
        had2 = new Had("HAD 2",Color.GREEN);
        zobrazDialog("Start","Pro začátek stiskněte tlačítko ..","Start",PrikazyHandler.START,0);
    }

    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            try {
                switch (prikazHandler[msg.what]){
                    case MISTNIHAD:
                        if(prvniZapnuto){
                            zapnuto = true;
                            prvniZapnuto = false;
                            tak1 = (int)System.currentTimeMillis();

                        }
                        if(zapnuto == true){
                           // try{
                                had1.spoctiBod();
                            /*}catch (ExHad e){
                                zobrazDialog(e.toString());
                            } */
                            kresli.pridejBod(had1);
                        }

                        //odeslatHandler(PrikazyHandler.VZDALENE,fps);
                        odeslatHandler(PrikazyHandler.MISTNIHAD,fps);
                        Log.d(TAG,"PING");
                        break;
                    case START:
                        if(!prvniZapnuto)
                            odeslatHandler(PrikazyHandler.START,500);
                        else
                        {
                            odeslatHandler(PrikazyHandler.MISTNIHAD,0);
                            odeslatHandler(PrikazyHandler.NAZIVOT,0);
                        }
                        break;
                    case KOLIZE:
                        zobrazDialog("kolize");
                        break;
                    case NAZIVOT:
                        if(zapnuto == true){
                            kresli.pridejPrekazku(had2.generujBod());
                            odeslatHandler(PrikazyHandler.NAZIVOT,fps*4);
                        }
                        break;
                    case VZDALENE:
                        if(zapnuto == true){
                            //try{
                                had2.spoctiBod();
                            /*}catch (ExHad e){
                                zobrazDialog(e.toString());
                            } */
                            kresli.pridejBod(had2);
                        }
                        //odeslatHandler(PrikazyHandler.VZDALENE,50);
                        break;
                    default:
                        Log.i(TAG, "Handle zadny přikaz, kod: " + msg.what);
                        break;
                }
            }
            catch (Exception x) {
                Log.e(TAG,"Handle ArrayIndexOutOfBoundsException exception: " + x.toString());
            }
        }
    };
    public void odeslatHandler(PrikazyHandler prikaz,int cas){
        handler.sendEmptyMessageDelayed(prikaz.ordinal(), cas);
    }
    public static void naKlik(Bod bod)
    {
        /*if(!prvniZapnuto)
            prvniZapnuto = true;*/
            //handler.sendEmptyMessageDelayed(PrikazyHandler.START.ordinal(), 0);
            //start();
        if (bod.y < maxBod.y / 2) {
            had1.zatocit(false);
            Log.d(TAG, "VLEVO");
        } else if (bod.y >= maxBod.y / 2) {
            had1.zatocit(true);
            Log.d(TAG, "VPRAVO");
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        finish();
    }

    @Override
    protected void onResume() {
        kresli.resume();
        super.onResume();
    }

    @Override
    protected void onStop() {
        super.onStop();
        finish();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        finish();
        Intent i = new Intent(this, GameActivity.class);
        startActivity(i);
        finish();
    }


    public static void zobrazDialog(String text)
    {
        zapnuto = false;
        dialog = new AlertDialog.Builder(kresli.contex).create();
        dialog.setTitle("GAME OVER");
        //alertDialog.setIcon(R.drawable.icon);
        dialog.setMessage(text);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {
                //StartActivity.pause();
            }
        });
        //
        dialog.show();
    }
    public void zobrazDialog(String nadpis,String text,String tlacitko,final PrikazyHandler prikaz, int cas)
    {
        zapnuto = false;

        dialog = new AlertDialog.Builder(KresliView.contex).create();
        dialog.setTitle(nadpis);
        //alertDialog.setIcon(R.drawable.icon);
        dialog.setMessage(text);
        dialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                odeslatHandler(prikaz,0);
            }
        });
        dialog.show();
    }
}

class Had {
    /////////////////////////////////////////////////////
    GameActivity GA;
    private static final String TAG = "DEBug";
    public Paint nastaveni = new Paint();
    public String nazev = "Had";
    //public static List<Bod> listBodu = new ArrayList<Bod>();
    public Bod novyBod;// = new Bod();
    public Otoceni smer = Otoceni.SEST;
    public enum Otoceni {
        JEDNA,
        DVA,
        TRI,
        CTIRI,
        PET,
        SEST,
        SEDM,
        OSM,
        DEVET,
        DESET,
        JEDENACT,
        DVANACT
    }
    //////////////////////////////////////////////////////
    Had() {
        novyBod = generujBod();
        smer = nahodnySmer();
        nastaveni.setColor(Color.RED);
        nastaveni.setAntiAlias(true);
    }
    Had(String _nazev, int barva) {
        nazev = _nazev;
        novyBod = generujBod();
        smer = nahodnySmer();
        nastaveni.setColor(barva);
        nastaveni.setAntiAlias(true);
    }
    public Otoceni nahodnySmer() {
        int count = Otoceni.values().length;
        Random r = new Random();
        return Otoceni.values()[r.nextInt(count)];
    }
    public Bod generujBod() {
        Bod r = new Bod();
        Random rx = new Random();
        Random ry = new Random();
        r.x = rx.nextInt(GA.maxBod.x-GA.okraj*2)+GA.okraj;
        r.y = ry.nextInt(GA.maxBod.y-GA.okraj*2)+GA.okraj;
        return r;
    }
    ////////////////////////////////////////////////////////
    public void zahniDoprava() {
        //Log.d(TAG,"smer je " + smer.toString());
        if (smer.ordinal() + 1 > Otoceni.values().length-1)
            smer = Otoceni.values()[0];
        else
            smer = Otoceni.values()[smer.ordinal() + 1];
        //Log.d(TAG,"smer po je " + smer.toString());
    }
    public void zahniDoleva() {
        if (smer.ordinal() - 1 < 0)
            smer = Otoceni.values()[Otoceni.values().length-1];
        else
            smer = Otoceni.values()[smer.ordinal() - 1];

    }
    public void zatocit(boolean doPrava) {
        if (doPrava)
            zahniDoprava();
        else
            zahniDoleva();
    }
    /////////////////////////////////////////////////////////
    //public boolean utelkVen() {
    public void utelkVen() {
        if (novyBod.x < GA.okraj || novyBod.y < GA.okraj || novyBod.x > GA.maxBod.x-GA.okraj || novyBod.y > GA.maxBod.y-GA.okraj) {
            Log.i(TAG, "Mimo pole: " + novyBod.toString());
            GA.zapnuto = false;
            //GA.zobrazDialog("mimo plochu");
            GA.zobrazDialog("Hráč " + nazev +" narazil do zdi na (" + novyBod.toString() + ")");
        }
        //return false;
    }
    ////////////////////////////////////////////////////////
    //public boolean spoctiBod() {
    public void spoctiBod() {
        switch (smer) {
            case JEDNA:
                novyBod.x++;
                novyBod.y+=2;
                break;
            case DVA:
                novyBod.x+=2;
                novyBod.y++;
                break;
            case TRI:
                novyBod.x+=3;
                break;
            case CTIRI:
                novyBod.x+=2;
                novyBod.y--;
                break;
            case PET:
                novyBod.x++;
                novyBod.y-=2;
                break;
            case SEST:
                novyBod.y-=3;
                break;
            case SEDM:
                novyBod.x--;
                novyBod.y-=2;
                break;
            case OSM:
                novyBod.x-=2;
                novyBod.y--;
                break;
            case DEVET:
                novyBod.x-=3;
                break;
            case DESET:
                novyBod.x-=2;
                novyBod.y++;
                break;
            case JEDENACT:
                novyBod.x--;
                novyBod.y+=2;
                break;
            case DVANACT:
                novyBod.y+=3;
                break;
            default:
                Log.e(TAG,"NOVY BOD - Blbosr ...");
                break;
        }
        //return !utelkVen();
        utelkVen();
    }
    public boolean spoctiBod(Bod bod) {
        novyBod = bod;
        return true;
    }
}

class Bod extends android.graphics.Point {
    int x, y;      //float

    Bod(){
        x = 0;
        y = 0;
    }
    Bod(int _x, int _y){
        x = _x;
        y = _y;
    }

    @Override
    public String toString() {
        return x + ", " + y;
    }

    public static Bod Plus(Bod a, Bod b) {
        Bod vysledek = new Bod();
        vysledek.x = a.x + b.x;
        vysledek.y = a.y + b.y;
        return vysledek;
    }

    public static Bod Minus(Bod a, Bod b) {
        Bod vysledek = new Bod();
        vysledek.x = a.x - b.x;
        vysledek.y = a.y - b.y;
        return vysledek;
    }
    public static Bod Deleno(Bod bod,int deleno){
        if(deleno > 0)
        {
            Bod vysledek = new Bod();
            vysledek.x = bod.x/deleno;
            vysledek.y = bod.y/deleno;
            return vysledek;
        }
        else
            return bod; //TODO: Bod Deleno - return if(deleno <= 0)   ??
    }
}